package config

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/lab-online/pkg/color"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

var RootPath string

func init() {
	configFile := "./config/app.yaml"
	pflag.String("initial", "./initial.json", "initial database data file path")
	pflag.StringVarP(&configFile, "config", "c", configFile, "config file path")
	pflag.Parse()

	pwd, _ := os.Getwd()
	if isE2E, exists := os.LookupEnv("IS_E2E"); exists && isE2E == "true" {
		pwd = filepath.Join(pwd, "..", "..")
		configFile = os.Getenv("E2E_CONFIG_FILE")
	}

	fmt.Println(color.PrefixInfo, "$PWD =", pwd)
	RootPath = pwd
	configFilePath := filepath.Join(pwd, configFile)
	setupConfig(configFilePath)
}

func unmarshalConfig() {
	viper.AutomaticEnv()
	viper.WatchConfig()

	setupServerConfig()
	setupCORSConfig()
	setupServiceConfig()
	setupLoggerConfig()
	setupGORMLoggerConfig()
	setupJWTConfig()
	setupOSSConfig()
}

func setupConfig(configFile string) {
	viper.SetConfigFile(configFile)

	if err := viper.ReadInConfig(); err != nil {
		fmt.Println(color.PrefixError, err)
		panic(err)
	}
	fmt.Println(color.PrefixInfo, "using config file", viper.ConfigFileUsed())

	unmarshalConfig()
}
